﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Web7.Container.Localization;
using Web7.Container.Services;


namespace Web7.Container.Controllers
{

    public class LanguageController : AdminController
    {
        #region Fields

        private readonly ILanguageService _languageService;
        private readonly ILocalizationService _localizationService;


        #endregion

        #region Constructors

        public LanguageController(ILanguageService languageService, ILocalizationService localizationService)
        {
            _localizationService = localizationService;
            _languageService = languageService;

        }

        #endregion

        #region Languages

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List(bool? isPublished = true)
        {
            var languages = _languageService.Fetch(p => p.Published == isPublished);

            return languages != null ? View("List", languages) : null;
        }


        public ActionResult Create()
        {
            var model = new Language { Id = SequentialGuid.NewGuid(), Published = true };
            //default values
            return View(model);
        }


        [HttpPost]
        public ActionResult Create(Language language)
        {


            if (ModelState.IsValid)
            {
                _languageService.Create(language);

                //SuccessNotification(_localizationService.GetResource("Admin.Configuration.Languages.Added"));
                return RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            return View(language);
        }

        public ActionResult Edit(Guid id)
        {


            var language = _languageService.Get(p => p.Id == id);
            if (language == null)
                //No language found 
                return RedirectToAction("List");
            return View(language);
        }
        [HttpPost]
        public ActionResult Edit(Language model)
        {

            var language = _languageService.Get(p => p.Id == model.Id);
            if (language == null)
                //No language found with the specified id
                return RedirectToAction("List");

            //language.DisplayOrder = model.DisplayOrder;
            //language.Name = model.Name;
            //language.LanguageCulture = model.LanguageCulture;
            //language.Published = model.Published;
          
            if (ModelState.IsValid)
            {
                _languageService.Update(model);

                // SuccessNotification(_localizationService.GetResource("Admin.Configuration.Languages.Updated"));
                return RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }


        public ActionResult Delete(Guid id)
        {


            var language = _languageService.Get(p => p.Id == id);
            if (language == null)
                //No language found with the specified id
                return RedirectToAction("List");
            _languageService.Delete(language);
            //SuccessNotification(_localizationService.GetResource("Admin.Configuration.Languages.Deleted"));
            return RedirectToAction("List");
        }

        #region Notification
        protected virtual void SuccessNotification(string message, bool persistForTheNextRequest = true)
        {
            AddNotification(NotifyType.Success, message, persistForTheNextRequest);
        }
        protected virtual void ErrorNotification(string message, bool persistForTheNextRequest = true)
        {
            AddNotification(NotifyType.Error, message, persistForTheNextRequest);
        }
        protected virtual void ErrorNotification(Exception exception, bool persistForTheNextRequest = true)
        {
            //  LogException(exception);
            AddNotification(NotifyType.Error, exception.Message, persistForTheNextRequest);
        }
        protected virtual void AddNotification(NotifyType type, string message, bool persistForTheNextRequest)
        {
            string dataKey = string.Format("nop.notifications.{0}", type);
            if (persistForTheNextRequest)
            {
                if (TempData[dataKey] == null)
                    TempData[dataKey] = new List<string>();
                ((List<string>)TempData[dataKey]).Add(message);
            }
            else
            {
                if (ViewData[dataKey] == null)
                    ViewData[dataKey] = new List<string>();
                ((List<string>)ViewData[dataKey]).Add(message);
            }
        }

        public enum NotifyType
        {
            Success,
            Error
        }


        #endregion


        #endregion

        //#region Resources

        public ActionResult Resources(string languageId)
        {
            ViewBag.LanguageId = languageId;
            Guid guid;
            if (Guid.TryParse(languageId, out guid))
            {
                var language = _languageService.Get(guid);
                if (language == null)
                    //No language found with the specified id
                    return RedirectToAction("List");
                var list = _localizationService.LoadResourceXml(language);
                if (list == null)
                    return RedirectToAction("List");

                return View(list);
            }
            return View();
        }

        public ActionResult ResourcesCreate(Guid languageId)
        {
            var model = new LocaleStringResource { Id = SequentialGuid.NewGuid(), LanguageId = languageId };
            //default values
            return View(model);
        }
        [HttpPost]
        public ActionResult ResourcesCreate(LocaleStringResource localeStringResource)
        {
            if (ModelState.IsValid)
            {
                //default values
                var language = _languageService.Get(localeStringResource.LanguageId);
                if (language == null)
                    //No language found with the specified id
                    return RedirectToAction("List");
                localeStringResource.Language = language;
                _localizationService.ResourceXmlCreate(localeStringResource);
                return RedirectToAction("Resources", "Language", localeStringResource);
            }
            return View(localeStringResource);
        }

        #region 暂时无用代码
        //[HttpPost, GridAction(EnableCustomBinding = true)]
        //public ActionResult Resources(int languageId, GridCommand command)
        //{
        //    if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
        //        return AccessDeniedView();

        //    var resources = _localizationService.GetAllResourcesByLanguageId(languageId).Select(x => x.Value)
        //        .Select(x => x.ToModel())
        //        .ForCommand(command);

        //    var model = new GridModel<LanguageResourceModel>
        //    {
        //        Data = resources.PagedForCommand(command),
        //        Total = resources.Count()
        //    };
        //    return new JsonResult
        //    {
        //        Data = model
        //    };
        //}

        //[GridAction(EnableCustomBinding = true)]
        //public ActionResult ResourceUpdate(LanguageResourceModel model, GridCommand command)
        //{
        //    if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
        //        return AccessDeniedView();

        //    if (model.Name != null)
        //        model.Name = model.Name.Trim();
        //    if (model.Value != null)
        //        model.Value = model.Value.Trim();

        //    if (!ModelState.IsValid)
        //    {
        //        //display the first model error
        //        var modelStateErrors = this.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
        //        return Content(modelStateErrors.FirstOrDefault());
        //    }

        //    var resource = _localizationService.GetLocaleStringResourceById(model.Id);
        //    // if the resourceName changed, ensure it isn't being used by another resource
        //    if (!resource.ResourceName.Equals(model.Name, StringComparison.InvariantCultureIgnoreCase))
        //    {
        //        var res = _localizationService.GetLocaleStringResourceByName(model.Name, model.LanguageId, false);
        //        if (res != null && res.Id != resource.Id)
        //        {
        //            return Content(string.Format(_localizationService.GetResource("Admin.Configuration.Languages.Resources.NameAlreadyExists"), res.ResourceName));
        //        }
        //    }

        //    resource = model.ToEntity(resource);
        //    _localizationService.UpdateLocaleStringResource(resource);

        //    return Resources(model.LanguageId, command);
        //}

        //[GridAction(EnableCustomBinding = true)]
        //public ActionResult ResourceAdd(int id, LanguageResourceModel model, GridCommand command)
        //{
        //    if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
        //        return AccessDeniedView();

        //    if (model.Name != null)
        //        model.Name = model.Name.Trim();
        //    if (model.Value != null)
        //        model.Value = model.Value.Trim();

        //    if (!ModelState.IsValid)
        //    {
        //        //display the first model error
        //        var modelStateErrors = this.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
        //        return Content(modelStateErrors.FirstOrDefault());
        //    }

        //    var res = _localizationService.GetLocaleStringResourceByName(model.Name, model.LanguageId, false);
        //    if (res == null)
        //    {
        //        var resource = new LocaleStringResource { LanguageId = id };
        //        resource = model.ToEntity(resource);
        //        _localizationService.InsertLocaleStringResource(resource);
        //    }
        //    else
        //    {
        //        return Content(string.Format(_localizationService.GetResource("Admin.Configuration.Languages.Resources.NameAlreadyExists"), res.ResourceName));
        //    }
        //    return Resources(id, command);
        //}

        //[GridAction(EnableCustomBinding = true)]
        //public ActionResult ResourceDelete(int id, int languageId, GridCommand command)
        //{
        //    if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
        //        return AccessDeniedView();

        //    var resource = _localizationService.GetLocaleStringResourceById(id);
        //    if (resource == null)
        //        throw new ArgumentException("No resource found with the specified id");
        //    _localizationService.DeleteLocaleStringResource(resource);

        //    return Resources(languageId, command);
        //}

        //#endregion

        //#region Export / Import

        //public ActionResult ExportXml(int id)
        //{
        //    if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
        //        return AccessDeniedView();

        //    var language = _languageService.GetLanguageById(id);
        //    if (language == null)
        //        //No language found with the specified id
        //        return RedirectToAction("List");

        //    try
        //    {
        //        var fileName = string.Format("language_{0}.xml", id);
        //        var xml = _exportManager.ExportLanguageToXml(language);
        //        return new XmlDownloadResult(xml, fileName);
        //    }
        //    catch (Exception exc)
        //    {
        //        ErrorNotification(exc);
        //        return RedirectToAction("List");
        //    }
        //}

        //[HttpPost]
        //public ActionResult ImportXml(int id, FormCollection form)
        //{
        //    if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
        //        return AccessDeniedView();

        //    var language = _languageService.GetLanguageById(id);
        //    if (language == null)
        //        //No language found with the specified id
        //        return RedirectToAction("List");

        //    //set page timeout to 5 minutes
        //    this.Server.ScriptTimeout = 300;

        //    try
        //    {
        //        var file = Request.Files["importxmlfile"];
        //        if (file != null && file.ContentLength > 0)
        //        {
        //            using (var sr = new StreamReader(file.InputStream, Encoding.UTF8))
        //            {
        //                string content = sr.ReadToEnd();
        //                _importManager.ImportLanguageFromXml(language, content);
        //            }

        //        }
        //        else
        //        {
        //            ErrorNotification("Please upload a file");
        //            return RedirectToAction("Edit", new { id = language.Id });
        //        }

        //        SuccessNotification(_localizationService.GetResource("Admin.Configuration.Languages.Imported"));
        //        return RedirectToAction("Edit", new { id = language.Id });
        //    }
        //    catch (Exception exc)
        //    {
        //        ErrorNotification(exc);
        //        return RedirectToAction("Edit", new { id = language.Id });
        //    }

        //}

        //#endregion
        #endregion
    }
}
